package com.example.demo.aop;

import com.example.demo.entity.Log;
import com.example.demo.producer.LogProducer;
import com.example.demo.util.IpUtil;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private LogProducer logProducer;

    @Before("execution (* com.example.demo.controller.*.*(..))")
    public void commitLog(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //封装LogIpUtil对象
        Log log = new Log();
        log.setClientIp(IpUtil.getIpAddr(request));
        log.setUrl(request.getRequestURL().toString());
        log.setRequestTime(new Date());
        log.setMethod(request.getMethod());

        logger.info("log content {}",log);

        logProducer.produceLog(log);
    }
}
